// pages/message/message.js
var cf2 = require("../../utils/config2");
var app = getApp();
var cf = require("../../config.js");
var changeTime = require("../../utils/changetime.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var employee = {};
//获取应用实例
var webim = global.webim;
var webimhandler = global.webimhandler;
var em = require("../../data_file/emtion")
import messageServ from "./messageServ";
var regeneratorRuntime = require("../../lib/js/runtime-module.js")
const pageManager = require('../../lib/js/pageManager');

Page({
  data: {
    staticResPath: cf.config.staticResPath,
    messageList: [],
    messagePageNo: 1,
    messagePageSize: 11,
    chatPageNo: 1,
    chatPageSize: 11,
    contactList: [],
    newMessageState: false,
    isShowContactList: true,
    isShowMessageList: false,
    startX: 0, //开始坐标
    startY: 0,
    requestShow: false
  },
  loadRecentContactList: async function (data) {
    let that = this;
    let openId = wx.getStorageSync('openId');
    employee = wx.getStorageSync("employee");

    let { isShowContactList, chatPageNo, chatPageSize, contactList } = this.data;
    let param = {
      openid: openId,
      start: chatPageNo,
      limit: chatPageSize,
      type: 1
    }
    let modelList = [];
    if (data) {
      modelList = data.model.list;
    } else {
      let list = await messageServ.queryMsgList(param);
      modelList = list.model ? list.model.list : []
    }
    isShowContactList = true;
    if (modelList && modelList.length > 0) {
      modelList.forEach(function (c) {
        changeTime.reset();
        var chatTime = changeTime.getHistoryTimer(c.msgTime) || "刚刚";
        c.date = chatTime;
        c.delName = "删除";
        c.isTouchMove = false;
        c.MsgShow = JSON.parse(c.msgContent);
        var msg = c.MsgShow;
        if (msg.msg.options && msg.card_id == employee.id) {
          if (msg.msg.context.indexOf("微信") != -1) {
            msg.msg.context = c.MsgShow.from_userinfo.nickName + "复制了你的微信"
          }
          if (msg.msg.context.indexOf("你已拨打了") != -1) {
            msg.msg.context = c.MsgShow.from_userinfo.nickName + "拨打了你的电话"
          }
          if (msg.msg.context.indexOf("名片") != -1) {
            msg.msg.context = c.MsgShow.from_userinfo.nickName + "保存了你的名片海报"
          }
          if (msg.msg.context.indexOf("授权电话") != -1) {
            msg.msg.context = c.MsgShow.from_userinfo.nickName + "授权电话成功 " + c.MsgShow.from_userinfo.phone
          }
        }

      })
    }
    if (chatPageNo == 1 && modelList.length == 0) {
      isShowContactList = false;
    }
    if (chatPageNo > 1) {
      contactList = [...contactList, ...modelList];
    } else {
      contactList = modelList
    }
    app.getAllUnreadNum('1', function (unReadMsgList) {
      if (unReadMsgList && unReadMsgList.length > 0) {
        for (var i = 0; i < unReadMsgList.length; i++) {
          var unReadMsg = unReadMsgList[i];
          for (var j = 0; j < modelList.length; j++) {
            var contact = modelList[j];
            if (unReadMsg.targetOpenid == contact.employeeOpenId) {
              contact.UnreadMsgCount = unReadMsg.unreadNum;
            }
          }
        }
      }
      that.setData({
        contactList: contactList, isShowContactList
      });

    });

  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    let { contactList } = this.data;
    if (e.changedTouches && e.changedTouches.length > 0) {
      this.setData({
        startX: e.changedTouches[0].clientX,
        startY: e.changedTouches[0].clientY,
        contactList
      })
    }

  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      { startX, startY, contactList } = this.data,
      index = e.currentTarget.dataset.index,//当前索引
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    contactList.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) {//右滑
          v.isTouchMove = false
          v.delName = '删除'
        }
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      contactList
    })
  },
  /**
  * 计算滑动角度
  * @param {Object} start 起点坐标
  * @param {Object} end 终点坐标
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  /**
   * 删除会话
   */
  del: function (e) {
    let { contactList, isShowContactList } = this.data;
    let chat_detail = wx.getStorageSync('chat_detail');
    let closeTipsUser = wx.getStorageSync('closeTipsUser');
    let { index, toaccount, fromaccount } = e.currentTarget.dataset
    let that = this;
    if (contactList[index].delName == '确认删除') {
      messageServ.delHistoryMsg({ type: "1", fromAccount: fromaccount, toAccount: toaccount, cusmallToken: wx.getStorageSync('cusmallToken') }).then((item) => {
        contactList.splice(index, 1)
        if (contactList.length == 0) { isShowContactList = false }
        if (chat_detail[fromaccount]) {//删除缓存
          delete chat_detail[fromaccount]
          wx.setStorageSync('chat_detail', chat_detail)
        }
        if (closeTipsUser[fromaccount]) { //删除提示弹出
          delete closeTipsUser[fromaccount]
          wx.setStorageSync('closeTipsUser', closeTipsUser)
        }
        app.getTotalUnreadNum(function () { }, that);
        that.setData({ contactList, isShowContactList })
      });
    } else {
      contactList[index].delName = '确认删除'
      that.setData({ contactList })
    }

  },
  /**
   * 跳转聊天室
   */
  onMsgSecTab: function (e) {
    let employeeId = e.currentTarget.dataset.id;
    let openId = e.currentTarget.dataset.openid;
    let cusmallToken = wx.getStorageSync('cusmallToken');
    const getEmployeeInfo = messageServ.getEmployeeInfo({cusmallToken,eid: employeeId})
    const fetchSig = messageServ.getUserSign({cusmallToken,identifier: openId})
    pageManager.putData('getEmployeeInfo', getEmployeeInfo);
    pageManager.putData('fetchSig', fetchSig);
    app.subscribeMessage(()=>{
      
      wx.navigateTo({ url: '/subPackages/pages/chat_detail/chat_detail?eId=' + employeeId });
  
    },cf.config.messageTemplateId);
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    webimhandler.setPageCtx(this);
    var that = this;
    let loadRecentContactList = pageManager.getData('loadRecentContactList');
    if (loadRecentContactList) {
      this.data.requestShow = true;
      loadRecentContactList.then((res) => {
        this.loadRecentContactList(res)
      });
    }
    that.setData({
      emtions: em.changeEm()
    })
  },
  setTime: function (time) {
    let date, hm
    time.split(' ').map((item, index) => {
      index == 0 ? date = item.split('-').filter((m, i) => i > 0).join('-') : hm = item.split(':').filter((m, i) => i < 2).join(':')
    })
    return `${date} ${hm}`
  },
  getMessageList: function () {
    const that = this;
    let { pageNo, pageSize } = this.data;
    wx.request({
      url: cf2.default.host + '/app/message/list',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('authName')
      },
      data: { pageNo, pageSize, mobile: wx.getStorageSync('phoneNo') },
      success: function (res) {
        if (res && res.data && res.data.rows.length > 0) {
          res.data.rows.map(item => {
            item.headPic = 'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/chat/housePayment.png'
            item.updateTime = item.updateTime ? that.setTime(item.updateTime) : ''
          })
          that.setData({
            messageList: [...that.data.messageList, ...res.data.rows],
            pageNo: that.data.params.pageNo,
            total: res.data.total,
            isShowMessageList: true

          })
        } else {
          that.setData({ isShowMessageList: false });
        }

      }
    })
  },
  toGwlist: function () {
    wx.navigateTo({ url: '/pages/consultant/consultant?pageType=message' })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    this.data.chatPageNo = 1
    if (!this.data.requestShow) {
      webimhandler.setNewMsgListener(function (newmsg) {
        that.loadRecentContactList();
      });
      app.getUserIMSign(() => {
        that.loadRecentContactList();
        app.getTotalUnreadNum(function () { }, that);
      });
    }
  },
  onHide() {
    this.data.requestShow = false
  },

  goCardList() {
    wx.navigateTo({
      url: '/pages/load/load'
    });
  }
  ,
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { messagePageNo, messageList, total, chatPageNo, contactList } = this.data;
    if (messageList.length < total) {
      messagePageNo += 1;
      this.setData({ messagePageNo })
      this.getMessageList();
    }
    if (contactList.length > 0) {
      chatPageNo += 1;
      this.setData({ chatPageNo })
      this.loadRecentContactList();
    }


  }
  ,
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '金科神器',
      path: '/pages/index/index'
    }
  }

})